<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrappe">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="单据来源" class="form-item">
              <j-dict-select-tag placeholder="请选择单据来源" @input="handleDocumentSource" v-model="queryParam.permissionType" dictCode="permission_type"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="queryParam.permissionType == 3">
            <a-form-item label="选择部门">
              <J-select-multiple
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                placeholder="请选择选择部门"
                :options="getDepartName"
                showId="id"
                v-model="queryParam.deptIds"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="queryParam.permissionType == 4">
            <a-form-item label="选择团队">
              <J-select-multiple
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                placeholder="请选择选择团队"
                :options="getTeamName"
                showId="id"
                v-model="queryParam.teamIds"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="单据编号" class="form-item">
              <j-input placeholder="请输入单据编号" v-model="queryParam.billNo"></j-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="申请公司" class="form-item">
                <select-Company-input placeholder="请选择申请公司" v-model="queryParam.companyId" />
              </a-form-item>
            </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="关联项目" class="form-item">
                <select-project-input v-model="queryParam.projectId" placeholder="请选择关联项目" />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="使用日期" class="form-item">
                <j-date placeholder="请选择使用日期" v-model="queryParam.useDate" style="width: 100%"></j-date>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="queryParam.permissionType != 4">
              <a-form-item label="借款所属团队" class="form-item">
                <select-team-input placeholder="请选择借款所属团队" v-model="queryParam.teamId" :teamType="0" :tdlx="3" />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="借款方式" class="form-item">
                <j-dict-select-tag placeholder="请选择借款方式" style="radio" v-model="queryParam.borrowMode" dictCode="borrow_money"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="归还日期" class="form-item">
                <j-date placeholder="请选择归还日期" v-model="queryParam.returnDate" style="width: 100%"></j-date>
              </a-form-item>
            </a-col>
          <!-- <template v-if="toggleSearchStatus"></template> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" :disabled="isDisabledAuth('erpFinanceLoanBill:add')">新增</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" :disabled="isDisabledAuth('erpFinanceLoanBill:delete')"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
      <a-popover title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <a-row>
              <template v-for="(item,index) in defColumns">
                <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                  <a-col :span="12" :key="index"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                </template>
              </template>
            </a-row>
          </a-checkbox-group>
        </template>
        <a style="float: right;"><a-icon type="setting" :style='iconStyle'/></a>
      </a-popover>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <div style="float: right;margin-bottom: 16px;"><span style="color:#1890FF;">累计未还金额：{{outstandingAmount}} 元</span></div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:scrollX}"
        :components="draggableComponent"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{getCheckboxProps:getCheckboxProps, selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        :customRow="customRow"
        @change="handleTableChange">
        <a slot="billNo" slot-scope="text, record" @click="getDetail(record.id)">{{ text }}</a>
        <a slot="projectId" slot-scope="text, record" @click="onDetail(record.projectId)">{{ text }}</a>
        <span slot="money" slot-scope="text, record">
          {{ record.amount?record.amount:0 }} /
          <a @click="getRepaymentAmount(record.id)">{{ record.repaymentAmount }}</a>
          /
          <a @click="getPaymentAmount(record.id)">{{ record.paymentAmount }}</a>
          / {{ ((record.amount?record.amount:0)-(record.repaymentAmount?record.repaymentAmount:0)-(record.paymentAmount?record.paymentAmount:0)).toFixed(2) }}
        </span>
        <span slot="notify" slot-scope="text, record">
          <a-icon title="催办提醒" v-if="record.taskUrge" theme="twoTone" twoToneColor="#eb2f96"
                  @click="taskNotifyMe(flowCode,record.id)" type="notification"/>
          {{ text }}
        </span>
        <template slot="status" slot-scope="status">
          <a-badge :status="status | statusTypeFilter" :text="status | statusFilter"/>
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
            <template v-if="record.bpmStatus === '1'">
            <a-button
                    class="ruleButton"
                    :ghost="true"
                    type="primary"
                    icon="edit"
                    @click="handleEdit(record)"
                    :disabled="isDisabledAuth('erpFinanceLoanBill:edit')"
            />
            <a-divider type="vertical"/>
            <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                <a-button
                        class="ruleButton"
                        :ghost="true"
                        type="primary"
                        icon="delete"
                        :disabled="isDisabledAuth('erpFinanceLoanBill:delete')"/>
            </a-popconfirm>
        </template>
        <template v-else-if="showBtn(record.bpmStatus)&&queryParam.bizTaskType=='1'">
            <a-button type="primary" size="small" @click="handleProcess(record)">办理</a-button>
            <a-divider type="vertical"/>
        </template>
        <template v-else-if="queryParam.bizTaskType=='2' && showBtn(record.bpmStatus)">
            <a-button type="primary" size="small" @click="taskNotify(flowCode,record.id)">催办</a-button>
            <a-divider type="vertical"/>
            <a-popconfirm title="确定要作废吗?" @confirm="() => invalidProcess(record)">
                <a-button type="primary" size="small" :disabled="isDisabledAuth('erpFinanceLoanBill:invalidProcess')">
                    作废流程
                </a-button>
            </a-popconfirm>
            <a-divider type="vertical"/>
        </template>
        <template v-if="record.bpmStatus !== '1'">
            <a-button type="primary" size="small" @click="handleTrack(record)" :disabled="isDisabledAuth('erpFinanceLoanBill:viewTrack')">审批进度</a-button>
        </template>
        </span>

      </a-table>
    </div>
    <erp-finance-loan-bill-modal ref="modalForm" @ok="modalFormOk"></erp-finance-loan-bill-modal>
    <bpm-biz-task-deal-modal ref="taskDealModal" :path="path" :formData="formData" @ok="handleOk"></bpm-biz-task-deal-modal>
    <bpm-process-track-modal ref="bpmProcessTrackModal"></bpm-process-track-modal>
    <biz-task-notify-modal ref="taskNotifyModal"></biz-task-notify-modal>
    <biz-task-notify-me-modal ref="taskNotifyMeModal"></biz-task-notify-me-modal>
    <erp-finance-repayment-slip-penetrate ref="repaymentSlip" />
    <erp-finance-travel-reimbursement-penetrate ref="reimbursementPenetrate" />
    <process-config-modal ref="processConfig" @ok="handleSuccess" @close="handleClose"></process-config-modal>
    <!-- 项目详情开始 -->
    <erp-project-report-modal  ref="projectForm"></erp-project-report-modal>
    <!-- 项目详情结束 -->
  </a-card>
</template>
<script>
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import {JeecgBpmListMixin} from '@/mixins/JeecgBpmListMixin'
import BpmBizTaskDealModal from "@/views/modules/bpmbiz/common/BpmBizTaskDealModal.vue";
import BpmProcessTrackModal from "@/views/modules/bpmbiz/common/BpmProcessTrackModal.vue";
import BizTaskNotifyModal from "@/views/modules/bpmbiz/common/BizTaskNotifyModal.vue";
import BizTaskNotifyMeModal from "@/views/modules/bpmbiz/common/BizTaskNotifyMeModal.vue";
import ErpFinanceLoanBillModal from './modules/ErpFinanceLoanBillModal'
import {DisabledAuthFilterMixin} from '@/mixins/DisabledAuthFilterMixin'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import ProcessConfigModal from '@/views/scy/components/ProcessConfigModal'
import ErpFinanceRepaymentSlipPenetrate from '@/views/scy/penetrate/ErpFinanceRepaymentSlipPenetrate'
import ErpFinanceTravelReimbursementPenetrate from '@/views/scy/penetrate/ErpFinanceTravelReimbursementPenetrate'
import {getAction} from '@/api/manage'
import { mapGetters } from 'vuex';
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  export default {
    name: 'ErpFinanceLoanBillList',
    mixins:[JeecgBpmListMixin, mixinDevice, DisabledAuthFilterMixin],
    components: {
      ErpProjectReportModal,
      ErpFinanceLoanBillModal,
      BpmBizTaskDealModal,
      BpmProcessTrackModal,
      BizTaskNotifyModal,
      BizTaskNotifyMeModal,
      SelectTeamInput,
      SelectProjectInput,
      ProcessConfigModal,
      ErpFinanceRepaymentSlipPenetrate,
      ErpFinanceTravelReimbursementPenetrate,
      SelectCompanyInput
    },
    data () {
      return {
        outstandingAmount:0,
        description: '借款单申请表管理页面',
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'单据编号',
            align:"center",
            dataIndex: 'billNo',
            scopedSlots: { customRender: 'billNo' },
            width:164,
            ellipsis: true
          },
          {
            title:'申请部门',
            align:"center",
            dataIndex: 'proposerDeptId_dictText',
            width:150,
            ellipsis: true,
          },
          {
            title:'申请公司',
            align:"center",
            dataIndex: 'companyId_dictText',
            width:200,
            ellipsis: true
          },
          {
            title:'借款所属团队',
            align:"center",
            dataIndex: 'teamId_dictText',
            width:120,
            ellipsis: true
          },
          {
            title:'关联项目',
            align:"center",
            dataIndex: 'projectId_dictText',
            scopedSlots: { customRender: 'projectId' },
            width:80,
            ellipsis: true
          },
          {
            title:'借款用途',
            align:"center",
            dataIndex: 'purpose_dictText',
            width:80,
            ellipsis: true
          },
          {
            title:'借款金额（元）/ 还款金额（元）/ 报销冲账（元）/ 未还金额（元）',
            align:"center",
            dataIndex: 'money',
            scopedSlots: { customRender: 'money' },
            width:500,
            ellipsis: true
          },
          {
            title:'使用日期',
            align:"center",
            dataIndex: 'useDate',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            },
            width:100,
            ellipsis: true
          },
          {
            title:'流程状态',
            align:"center",
            dataIndex: 'bpmStatus_dictText',
            width:80,
            ellipsis: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            width:147,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        url: {
          list: "/api/erp/finance/borrow/erpFinanceLoanBill/list",
          delete: "/api/erp/finance/borrow/erpFinanceLoanBill/delete",
          deleteBatch: "/api/erp/finance/borrow/erpFinanceLoanBill/deleteBatch",
          exportXlsUrl: "/api/erp/finance/borrow/erpFinanceLoanBill/exportXls",
          importExcelUrl: "api/erpfinance/borrow/erpFinanceLoanBill/importExcel",
          bizCount: "/api/erp/finance/borrow/erpFinanceLoanBill/bizCount",
          queryByProjectId: '/api/erp/project/report/erpProjectReport/queryById',
          gainBorrowMoney: "/api/erp/finance/borrow/erpFinanceLoanBill/gainBorrowMoney",
        },
        //代码生成后需手动设置流程编码
        flowCode: 'onl_erp_finance_loan_bill',
        formUrl: "/erp/finance/borrow/modules/ErpFinanceLoanBillForm",
        formUrlMobile: "/pages/synergy/loanBill",
        dictOptions:{},
        superFieldList:[],
        processId: '1519139387793809409',
        beanName:"erpFinanceLoanBillServiceImpl"
      }
    },
    created() {
      this.getSuperFieldList();
      //加载数据字典信息
      // this.initDictConfig();
      this.gainBorrowMoney();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      ...mapGetters(['userInfo']),
      gainBorrowMoney(){
        let that=this;
        let proposer=this.userInfo().empId;
        getAction(this.url.gainBorrowMoney, { proposer: proposer,  amount: 0}).then((res)=>{
          if(res.success){
            that.borrowMoney = res.result['borrowMoney']//可借金额
            that.canBorrow = res.result['canBorrow']//最大借款金额
            that.num = res.result['num']//未还完借款单数量
            that.outstandingAmount = res.result['outstandingAmount']//未还金额
            that.freezeAmount = res.result['freezeAmount']//冻结金额
          }
        })
      },
      beginProcess(record) {
        this.$refs.processConfig.visible = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(record, '',this.beanName)
      },
      handleSuccess() {
        this.loadData();
        this.onClearSelected();
        this.$refs.modalForm.handleCancel()
      },
      // 新增流程取消关闭弹窗刷新页面
    handleClose () {
      this.$refs.modalForm.handleCancel()
      this.loadData();
    },
      //流程审批结束禁用
      getCheckboxProps(record) {
        return {
          props: {
            disabled: record.bpmStatus !== "1"
          }
        }
      },
      //查看详情
      getDetail(id) {
        this.$router.push({
          path: `/erp/finance/borrow/ErpFinanceLoanBillListDetail/${id}`,
        })
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'billNo',text:'单据编号',dictCode:''})
        fieldList.push({type:'string',value:'teamId',text:'借款所属团队',dictCode:''})
        fieldList.push({type:'string',value:'projectId',text:'关联项目',dictCode:''})
        fieldList.push({type:'string',value:'purpose',text:'借款用途',dictCode:''})
        fieldList.push({type:'string',value:'money',text:'借款金额/还款金额/报销冲账',dictCode:''})
        fieldList.push({type:'date',value:'useDate',text:'使用日期'})
        fieldList.push({type:'string',value:'bpmStatus',text:'流程状态',dictCode:''})
        this.superFieldList = fieldList
      },
      // 打开还款金额明细弹窗
      getRepaymentAmount(billId) {
        //先清空数据
        this.$refs.repaymentSlip.dataSource = []
        this.$refs.repaymentSlip.ipagination.total = 0
        //查询数据
        this.$refs.repaymentSlip.loading = true
        this.$refs.repaymentSlip.loanBillId = billId
        this.$refs.repaymentSlip.searchReset()
        //打开弹窗
        this.$refs.repaymentSlip.visible = true
      },
      // 打开报销冲账明细弹窗
      getPaymentAmount(billId){
        //查询数据
        this.$refs.reimbursementPenetrate.loanBillId = billId
        this.$refs.reimbursementPenetrate.activeKey = '1'
        this.$refs.reimbursementPenetrate.callback(1)
        //打开弹窗
        this.$refs.reimbursementPenetrate.visible = true
        this.$refs.reimbursementPenetrate.reseting()
      },
      onDetail(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryByProjectId, { id: id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectForm.getDetail(model);
              that.$refs.projectForm.title = '项目一览表';
            }
          })
        })
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
